#ifndef WHTTPSERVER_H
#define WHTTPSERVER_H

#include "../common.h"
#include "wresourcemanager.h"
#include "networkframemanager.h"

#include <mutex>          // 必须包含
#include <shared_mutex>   // 必须包含（C++17）
#include <map>
#include <wx/socket.h>

struct HttpClientInfo
{
    HttpClientInfo()
        : client(NULL) {}
    HttpClientInfo(wxSocketBase* pclient,wxDateTime time,wxString phearder)
        : client(pclient),lastActiveTime(time),hearder(phearder) {}

    wxSocketBase* client;
    wxString hearder;
    wxDateTime lastActiveTime;
};

// HTTP请求解析类
class WHttpRequest
{
public:
    WHttpRequest(const wxString& rawRequest);

    bool IsValid() const { return m_isValid; }
    wxString GetMethod() const { return m_method; }
    wxString GetPath() const { return m_path; }
    wxString GetHeader(const wxString& name) const;
    wxString GetParam(const wxString& name) const;
    wxString GetAcceptHeader() const { return GetHeader("accept"); }
    std::map<wxString, wxString> GetAllParams() const { return m_params; }
    wxString GetBody() const { return m_body; }
    bool IsRealFaviconRequest(void) const;
    bool IsKeepLive(void) const;
    bool IsPageRequest() const;

private:
    void ParseRequest(const wxString& rawRequest);
    void ParseQueryParams(const wxString& queryString);

    bool m_isValid;
    wxString m_method;
    wxString m_path;
    std::map<wxString, wxString> m_headers;
    std::map<wxString, wxString> m_params;
    wxString m_body;
};

// HTTP响应生成类
class WHttpResponse
{
public:
    WHttpResponse();
    ~WHttpResponse();

    void SetStatus(int code, const wxString& message);
    void SetHeader(const wxString& name, const wxString& value);
    void SetContent(const wxString& content, const wxString& contentType = wxT("text/html; charset=utf-8"));
    void SetBinaryContent(const wxMemoryBuffer& content, const wxString& contentType);
    wxString ToString() const;
    const wxString& GetContent() const { return m_content; }
    int GetStatusCode() const { return m_statusCode; }
    bool IsBinary() const { return m_isBinary; }
    const wxString& GetStatusMessage() const { return m_statusMessage; }
    const wxMemoryBuffer& GetBinaryContent() const { return m_binaryContent; }
    const std::map<wxString, wxString>& GetHeaders() const { return m_headers; }

private:
    int m_statusCode;
    wxString m_statusMessage;
    std::map<wxString, wxString> m_headers;
    wxString m_content;
    wxMemoryBuffer m_binaryContent;
    bool m_isBinary;
};

class WHttpServer : public wxEvtHandler
{
public:
    WHttpServer();
    ~WHttpServer();

    /// 开始服务器
    bool Open(wxString ip,int port);
    /// 关闭服务器
    void Close(void);
    /// 设置网络处理框架
    inline void setNetworkFrameManager(NetworkFrameManager *manager) { mNetworkFrameManager = manager; }
    /// 客户端发送数据
    bool ClientSendData(wxSocketBase* client,const char* data, unsigned int datalength);
    /// 安全的响应发送方法
    bool SendResponse(wxSocketBase* client, const WHttpResponse& response);
    /// 设置工作目录
    inline void setWorkingPath(wxString path) { mWorkingPath = path; }

private:
    void OnServerEvent(wxSocketEvent& event);
    void OnHeartTimeOutTimer(wxTimerEvent& event);
    HttpClientInfo* getHttpClientInfo(wxSocketBase* client);

    // 带错误处理的Accept方法
    wxSocketBase* AcceptWithErrorHandling(bool wait=true);
    void ProcessClientRequest(wxSocketBase* client);
    void GenerateHTTPResponse(const WHttpRequest& request, WHttpResponse& response);
    void CloseAndRemoveClient(wxSocketBase* client, bool normalClose);
    bool isExistClientHearder(wxString hearder);
    void setClientHearder(wxSocketBase* client,wxString hearder);

private:
    wxString mServerIP;                                /**< 服务器IP */
    int mServerPort;                                   /**< 服务器端口 */
    wxTimer *m_HeartTimeOutTimer;                      /**< 心跳定时器 */
    wxSocketServer* mServer;
    WResourceManager mResourceManager;                 /**< 资源管理器 */
    std::map<int,HttpClientInfo> mClients;
    NetworkFrameManager *mNetworkFrameManager;         /**< 网络处理框架 */
    wxString mWorkingPath;                             /**< 当前工作目录 */
    mutable std::mutex m_ClientMutex;
};

#endif // WHTTPSERVER_H
